<?php

namespace App;

use App\Common\Util\Str;

/**
 * 继承系统的路由定义组件，主要增加可以直接使用数组的方式定义路由
 *
 * Class Route
 * @method static resourceSc(string $prefix, string $controller, array $exclude = [])
 */
class Route extends \think\facade\Route
{
    /**
     * @param $method
     * @param $params
     * @return mixed|void
     */
    public static function __callStatic($method, $params)
    {
        if ($method === 'resourceSc') {
            self::resourceScOrigin(...$params);
            return;
        }

        if (in_array(strtolower($method), ['get', 'post', 'rule']) && is_array($params[1])) {
            $params[1] = implode('@', $params[1]);
        }

        return parent::__callStatic($method, $params);
    }

    /**
     * 基于本系统的资源路由定义
     *
     * @param string $prefix 前缀
     * @param string<class-string> $controller 控制器名
     * @param array<string> $exclude 排除的路由
     * @return void
     */
    private static function resourceScOrigin(string $prefix, string $controller, array $exclude = []): void
    {
        $getMethods    = ['lists', 'listsData', 'create', 'edit'];
        $postMethods   = ['store', 'update', 'destroy'];
        $methodMapping = ['store' => 'create', 'edit' => 'update'];

        array_map(fn($method) => self::get(implode('/',[$prefix, Str::kebab($methodMapping[$method] ?? $method)]), [$controller, $method]), array_diff($getMethods, $exclude));
        array_map(fn($method) => self::post(implode('/',[$prefix, $methodMapping[$method] ?? $method]), [$controller, $method]), array_diff($postMethods, $exclude));
    }
}